package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 转型
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 1:插入订单表
        Order order = new Order();
        String orderId = UUID.randomUUID().toString();
        String id = globalIdGeneratorUtil.getNextSeq(orderId, 1);

        order.setOrderId(id);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        // 初始化订单状态
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);

        int effectRows = orderMapper.insert(order);
        if (effectRows != 1) {
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }

        // 2:插入商品关联表
        List<Long> byProductIds = new ArrayList<>();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProduct : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            String id2 = globalIdGeneratorUtil.getNextSeq(orderId, 1);
            orderItem.setId(id2);
            orderItem.setOrderId(id);
            orderItem.setItemId(cartProduct.getProductId());
            orderItem.setNum(cartProduct.getProductNum().intValue());
            orderItem.setPrice(cartProduct.getSalePrice().doubleValue());
            orderItem.setTitle(cartProduct.getProductName());
            orderItem.setPicPath(cartProduct.getProductImg());
            BigDecimal totalFee = cartProduct.getSalePrice().multiply(new BigDecimal(cartProduct.getProductNum()));
            orderItem.setTotalFee(totalFee.doubleValue());
            orderItem.setStatus(1);

            byProductIds.add(cartProduct.getProductId());
            int effectRows2 = orderItemMapper.insert(orderItem);
            if (effectRows2 != 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
            }
        }

        // 3:设置上下文
        createOrderContext.setOrderId(id);
        createOrderContext.setBuyProductIds(byProductIds);

        return true;
    }

}
